const request = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json'
    },
    withCredentials: true
});

request.interceptors.request.use(
    config => {
        const token = localStorage.getItem('accessToken');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }

        if (config.data instanceof FormData) {
            delete config.headers['Content-Type'];
        }

        return config;
    },
    error => {
        console.error('请求错误：', error);
        return Promise.reject(error);
    }
);

request.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.code !== 200) {
            if (res.code === 401 || res.message?.includes('token已经过期')) {
                localStorage.removeItem('accessToken');
                localStorage.removeItem('userInfo');

                return Swal.fire({
                    icon: 'warning',
                    title: '登录已过期',
                    text: '请重新登录',
                    confirmButtonText: '确定',
                    confirmButtonColor: '#546d9e',
                    allowOutsideClick: false
                }).then(() => {
                    window.location.href = 'login.html';
                    return Promise.reject(new Error(res.message || '登录已过期'));
                });
            }
            return Promise.reject(new Error(res.message || '请求失败'));
        }
        return res;
    },
    error => {
        if (error.response) {
            const status = error.response.status;
            const message = error.response.data?.message;

            if (status === 401 || message?.includes('token已经过期')) {
                localStorage.removeItem('accessToken');
                localStorage.removeItem('userInfo');

                return Swal.fire({
                    icon: 'warning',
                    title: '登录已过期',
                    text: '请重新登录',
                    confirmButtonText: '确定',
                    confirmButtonColor: '#546d9e',
                    allowOutsideClick: false
                }).then(() => {
                    window.location.href = 'login.html';
                });
            }

            Swal.fire({
                icon: 'error',
                title: '请求失败',
                text: message || '服务器异常，请稍后重试',
                confirmButtonColor: '#546d9e'
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: '网络错误',
                text: '请检查网络连接',
                confirmButtonColor: '#546d9e'
            });
        }
        return Promise.reject(error);
    }
);

window.request = request;